package org.lanyu.springainovel.chat.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.lanyu.springainovel.common.entity.SpringAIChatMemory;
import org.lanyu.springainovel.common.entity.ChatSessionHistory;
import org.lanyu.springainovel.chat.mapper.ChatMemoryMapper;
import org.lanyu.springainovel.chat.mapper.ChatSessionHistoryMapper;
import org.lanyu.springainovel.chat.vo.QuestionVO;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天记忆服务类（合并了ChatMemoryService和SpringAIChatMemoryService�? * 用于操作 spring_ai_chat_memory �? */
@Service
public class ChatMemoryService {
    @Autowired
    private ChatMemoryMapper chatMemoryMapper;

    @Autowired
    private ChatSessionHistoryMapper sessionHistoryRepository;

    @Autowired
    private ChatMemory chatMemory;

    public ChatMemoryService() {
        super();
    }

    /**
     * 保存用户消息（来自QuestionVO�?     */
    public void saveOrUpdateSessionHistory(QuestionVO questionVO) {
        QueryWrapper<ChatSessionHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", questionVO.getSessionId());
        ChatSessionHistory sessionHistory = sessionHistoryRepository.selectOne(queryWrapper);

        String title = questionVO.getMessage().length() > 20 ? questionVO.getMessage().substring(0, 20) : questionVO.getMessage();
        if (sessionHistory == null) {
            ChatSessionHistory session = new ChatSessionHistory();
            session.setSessionId(questionVO.getSessionId());
            session.setUserId(questionVO.getUserId());
            session.setTitle(title);
            session.setStatus(1);
            session.setUpdateTime(LocalDateTime.now());
            session.setUpdateTime(LocalDateTime.now());
            sessionHistoryRepository.insert(session);
        } else if (questionVO.getContentIndex() != null && questionVO.getContentIndex() == 0) {
            //清空消息后的首次提问
            sessionHistory.setTitle(title);
            sessionHistory.setUpdateTime(LocalDateTime.now());
            sessionHistoryRepository.updateById(sessionHistory);
        }

        //统一清除指定索引之后的记�?        chatMemoryMapper.deleteFromContentIndex(questionVO.getSessionId(), questionVO.getContentIndex());
    }

    /**
     * 获取会话的最近N条记�?     *
     * @param conversationId 会话ID
     * @param limit          限制条数
     * @return 聊天记录列表
     */
    public List<SpringAIChatMemory> getRecentMessages(String conversationId, int limit) {
        return chatMemoryMapper.getRecentMessages(conversationId, limit);
    }

    /**
     * 获取会话的详细历史记�?     *
     * @param conversationId 会话ID
     * @return 排序后的聊天记录
     */
    public List<SpringAIChatMemory> getSessionDetail(String conversationId) {
        return chatMemoryMapper.getAllMessages(conversationId);
    }

    /**
     * 清除会话对话记录
     */
    public void clearSessionHistory(String sessionId) {
        chatMemory.clear(sessionId);
    }
}
